package com.mayo.series.comun;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jeremyfeinstein.slidingmenu.lib.app.SlidingActivity;
import com.mayo.series.R;
import com.mayo.series.json.JSONParser;
import com.mayo.series.json.objects.NoticiaObject;

public class BaseMainActivity extends SlidingActivity {

	public ListView listaNoticias;
	public static NoticiasAdapter adapter;
	public static JSONParser jParser = new JSONParser();
	public static JSONArray noticias = null;
	public ProgressDialog pDialog;
	
	public static final String TAG_SUCCESS = "success";
	public static final String TAG_NOTICIAS = "noticias";
	public static final String TAG_ID = "id";
	public static final String TAG_NOMBRE = "titulo";
	public static final String TAG_TEXTO = "texto";
	public static final String TAG_IMAGEN = "imagen";
	public static final String TAG_FECHA = "fecha";
	
	/**
	 * Background Async Task to Load all product by making HTTP Request
	 * */
	public class LoadAllNoticias extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
//			pDialog = new ProgressDialog(BaseMainActivity.this);
//			pDialog.setMessage("Cargando el listado de series.");
//			pDialog.setIndeterminate(false);
//			pDialog.setCancelable(false);
//			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		protected String doInBackground(String... args) {
			String error = "0";
			List<NameValuePair> params;
			JSONObject json = new JSONObject();
			try {
				params = new ArrayList<NameValuePair>();
//				params.add(new BasicNameValuePair("comunidad", args[0]));
				json = jParser.makeHttpRequest(ComunUtilidades.URL_GET_NOTICIAS, "GET", params);
				Log.d("Mis series: ", json.toString());
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					noticias = json.getJSONArray(TAG_NOTICIAS);
					adapter = new NoticiasAdapter(noticias.length(), getApplicationContext());

					// looping through All Products
					for (int i = 0; i < noticias.length(); i++) {
						JSONObject c = noticias.getJSONObject(i);
						
						int id = c.getInt(TAG_ID);
						String titulo = c.getString(TAG_NOMBRE);
						String texto = c.getString(TAG_TEXTO);
						String imagen = ComunUtilidades.SERVIDOR_IMAGENES + c.getString(TAG_IMAGEN);
						String fecha = ComunUtilidades.formatDateString(c.getString(TAG_FECHA), "yyyy-mm-dd", "dd-mm-yyyy");
						
						NoticiaObject noticia = new NoticiaObject(id, titulo, texto, imagen, fecha);
						adapter.addItem(noticia);
					}
				}
			} catch (JSONException e) {
				e.printStackTrace();
				error = "1";
			} catch (RuntimeException e) {
				e.printStackTrace();
				error = "1";
			}

			return error;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(final String error) {
			// dismiss the dialog after getting all products
//			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
			 public void run() {
				if (error.equals("0")) {
//					listaAgrupaciones.setAdapter(adapter);
					listaNoticias.setAdapter(adapter);
				} else {
					Toast.makeText(getApplicationContext(), getString(R.string.error_conexion),
							Toast.LENGTH_LONG).show();
				}
			 }
			});

		}
	}
	
	/**
	 * Clase que controla el contenido y acciones de la lista de lugares.
	 * 
	 * @author masuar
	 * 
	 */
	public class NoticiasAdapter extends BaseAdapter {
		
        
        private HashMap<Integer, ImageView> views;
		private HashMap<Integer, ProgressBar> viewsProgress;
	    private HashMap<String,Bitmap> oldPicts = new  HashMap<String,Bitmap>();
	    boolean auto;

	    private final String BUNDLE_URL = "url";
	    private final String BUNDLE_BM = "bm";
	    private final String BUNDLE_POS = "pos";
	    private final String BUNDLE_ID = "id";
	    
		public final ViewHolder holder = new ViewHolder();
		private ArrayList<NoticiaObject> noticia = new ArrayList<NoticiaObject>();
		private LayoutInflater inflater;
		private Context context;
		
		public NoticiasAdapter(int size, Context context) {
			inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.context = context;
			inflater = LayoutInflater.from(context);
			views = new HashMap<Integer, ImageView>();
			viewsProgress = new HashMap<Integer, ProgressBar>();
		}

		public void addItem(final NoticiaObject lugar) {
			noticia.add(lugar);
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return noticia.size();
		}

		@Override
		public NoticiaObject getItem(int position) {
			return noticia.get(position);
		}
		
		public void setItem(int position, NoticiaObject agrupacion) {
			noticia.set(position, agrupacion);
		}

		@Override
		public long getItemId(int position) {
			return noticia.get(position).getId();
		}
		
		public int getItemPositionById(int id) {
			int position = -1;
			for (NoticiaObject serie : noticia) {
				if (serie.getId() == id)
					position = noticia.indexOf(serie);
			}
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {

            	convertView = inflater.inflate(R.layout.list_noticias, null);
            	convertView.setClickable(true);
            	
				// 	Obtenemos las referencias a los distintos controles
				holder.imagen = (ImageView) convertView.findViewById(R.id.imagen_noticia);
				holder.progress =  (ProgressBar) convertView.findViewById(R.id.progress);
				holder.titulo = (TextView) convertView.findViewById(R.id.titulo);
				holder.texto = (TextView) convertView.findViewById(R.id.texto);
				holder.fecha = (TextView) convertView.findViewById(R.id.fecha);
				
				holder.titulo.setText(noticia.get(position).getTitulo());
				holder.texto.setText(noticia.get(position).getTexto());
				holder.fecha.setText(noticia.get(position).getFecha());
				
//				Descargamos la imagen en otro hilo
				Bundle b = new Bundle();
	             b.putString(BUNDLE_URL, noticia.get(position).getImagen());
	             b.putInt(BUNDLE_POS, position);
	             b.putString(BUNDLE_ID, String.valueOf(noticia.get(position).getId()));
	             views.put(position, holder.imagen);
	             viewsProgress.put(position, holder.progress);
	        
	             new DownloadImagePrevia().execute(b);
			
			convertView.setTag(holder);
			return convertView;
		}

			// This is called when doInBackground() is finished
			public void onPostExecute(final Bundle result) {
				onPostExecute(result);
				 runOnUiThread(new Runnable() {
					 public void run() {
						 //get picture saved in the map + set
					 }
				 });
			}
	

	public class DownloadImagePrevia extends AsyncTask<Bundle, Bundle, Bundle> {
		// Do the long-running work in here

		public Bundle doInBackground(Bundle... b) {
			Bitmap bm = null;
			try {
				//cache: for better performance, check if url alredy exists
	            if (oldPicts.get(b[0].getString(BUNDLE_ID)) == null){
	            	bm = TratamientoImagenComun.decodeSampledBitmapFromUri(b[0].getString(BUNDLE_URL), 
	            			getResources().getIntArray(R.array.grid_celda)[0], getResources().getIntArray(R.array.grid_celda)[0]);
	                oldPicts.put(b[0].getString(BUNDLE_ID),bm);
	            } else {
	                bm = oldPicts.get(b[0].getString(BUNDLE_ID));
	            }
	            Bundle bundle = new Bundle();
	            bundle.putParcelable(BUNDLE_BM, bm);
	            bundle.putInt(BUNDLE_POS, b[0].getInt(BUNDLE_POS));

	            return bundle;
			} catch (NullPointerException e) {
			} catch (Exception e) {
			}
			return null;
		}

		// This is called when doInBackground() is finished
		public void onPostExecute(final Bundle result) {
			super.onPostExecute(result);
			 runOnUiThread(new Runnable() {
				 public void run() {
					 //get picture saved in the map + set
					 ImageView view = views.get(result.getInt(BUNDLE_POS));
					 ProgressBar progress = viewsProgress.get(result.getInt(BUNDLE_POS));
					 Bitmap bm = (Bitmap) result.getParcelable(BUNDLE_BM);
					 if (bm != null){ //if bitmap exists...
						 view.setImageBitmap(bm);
						 progress.setVisibility(ProgressBar.GONE);
						 view.setImageBitmap(bm);
						 view.setVisibility(ImageView.VISIBLE);
					 } else { //if not picture, display the default ressource
						 view.setImageResource(R.drawable.ic_launcher);
						 progress.setVisibility(ProgressBar.GONE);
						 view.setVisibility(ImageView.VISIBLE);
					 }
				 }
			 });
		}
	}
	}
	
	public static class ViewHolder {
		private ImageView imagen;
		private ProgressBar progress;
		private TextView titulo;
		private TextView texto;
		private TextView fecha;
	}
}
